package com.xh.core.util;

import com.xh.core.sms.dto.http.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author Pitt zhang
 * @since 2019/10/29
 */
public class SendMsgUtils {

    /**
     * appId
     */
    private static final String APP_ID = "aixue";

    /**
     * 密钥
     */
    private static final String SECRET_KEY = "o4higdsv";

    /**
     * 接口地址
     */
    private static final String HOST = "http://210.51.191.35:8080";
    /**
     * 时间戳
     */
    private static String TIMESTAMP = "";

    /**
     * 签名
     */
    private static String SIGN ="";

    /**
     * 发送验证码
     *
     * @param mobile
     */
    public static String sendCheckCode(String mobile, String checkCode) {
        TIMESTAMP = DateUtils.format(new Date(), "YYYYMMddHHmmss");
        SIGN = MD5Utils.string2MD5((MD5Utils.string2MD5(SECRET_KEY)) + TIMESTAMP);
        String content = "【小禾科技】您的验证码是：" + checkCode + "，请在5分钟内完成验证。";
        return setSms(APP_ID, SIGN, TIMESTAMP, HOST, content, mobile);
    }

    public static void main(String[] args) {

    }

    private static String setSms(String appId, String sign, String timestamp, String host, String content, String mobiles) {
        long balance = getBalance(appId, sign, timestamp, host);
        if (balance <= 0) {
            return "短信余额不足";
        }
        System.out.println("============= setSms==================");
        Map<String, String> params = new HashMap<>();
        params.put("name", appId);
        params.put("seed", timestamp);
        params.put("key", sign);
        params.put("dest", mobiles);
        params.put("content", content);

        String json = request(params, host + "/eums/sms/send.do");
        if (json != null) {
            String[] datas = json.split(":");
            if (!"success".equals(datas[0])) {
                System.out.println("短信发送失败，状态码：" + datas[1]);
            }
        }
        System.out.println("=============end setSms==================");
        return null;
    }

    /**
     * 公共请求方法
     */
    public static String request(Map<String, String> params, String url) {
        HttpRequestParams<Map<String, String>> requestparams = new HttpRequestParams<Map<String, String>>();
        //快用短信 必须要GBK编码，form传参
        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-type", "application/x-www-form-urlencoded");

        requestparams.setCharSet("GBK");
        requestparams.setMethod("POST");
        requestparams.setHeaders(headMap);
        requestparams.setParams(params);
        requestparams.setUrl(url);
        HttpRequest<Map<String, String>> request;
        if (url.startsWith("https://")) {
            request = new HttpsRequestKV(requestparams, null);
        } else {
            request = new HttpRequestKV(requestparams);
        }
        HttpClient client = new HttpClient();
        String json = null;
        try {
            String mapst = "";
            for (String key : params.keySet()) {
                String value = params.get(key);
                mapst += key + "=" + value + "&";
            }
            mapst = mapst.substring(0, mapst.length() - 1);
            System.out.println("request params: " + mapst);
            HttpResponseString res = client.service(request, new HttpResponseStringPraser());
            if (res == null) {
                System.err.println("请求接口异常");
                return null;
            }
            if (res.getResultCode().equals(HttpResultCode.SUCCESS)) {
                if (res.getHttpCode() == 200) {
                    json = res.getResult();
                    System.out.println("response json: " + json);
                } else {
                    System.out.println("请求接口异常,请求码:" + res.getHttpCode());
                }
            } else {
                System.out.println("请求接口网络异常:" + res.getResultCode().getCode());
            }
        } catch (Exception e) {
            System.err.println("解析失败");
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 获取余额
     */
    private static long getBalance(String appId, String sign, String timestamp, String host) {
        System.out.println("=============begin getBalance==================");
        Map<String, String> params = new HashMap<String, String>();
        params.put("name", appId);
        params.put("seed", timestamp);
        params.put("key", sign);
        String json = request(params, host + "/eums/sms/balance.do");
        if (!StringUtils.isEmpty(json)) {
            String[] datas = json.split(":");
            if ("success".equals(datas[0])) {
                return Long.parseLong(datas[1]);
            } else {
                System.out.println("查询余额失败，状态码：" + datas[1]);
            }
        }
        System.out.println("=============end getBalance==================");
        return 0l;
    }
}
